package com.hqyj.lyf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.hqyj.lyf.service.MsmService;
import com.hqyj.lyf.utils.ResultInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author: Chao
 * @description:
 * @Date: 2021/9/1 13:03
 */
@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public ResultInfo send(Map<String, Object> param, String phone) {
        // 判断号码是否为空
        if(StringUtils.isEmpty(phone)) {
            return new ResultInfo(-1,"电话号码为空",null);
        }

        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5tQCgF6b2dG9B3B2nCXG", "mBIT9uQDAeYufgKSFFP0glF4kZftGt");
        IAcsClient client = new DefaultAcsClient(profile);

        // 设置相关参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 设置发送的相关参数
        request.putQueryParameter("PhoneNumbers", phone); // 手机号
        request.putQueryParameter("SignName", "rotor管理"); // 设置签名名称
        request.putQueryParameter("TemplateCode", "SMS_209470757"); // 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        try {
            // 发送
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            boolean success = response.getHttpResponse().isSuccess();
            if (success){
                return new ResultInfo(200,"发送手机验证码成功",phone);
            }else {
                return new ResultInfo(-2,"发送失败",phone);
            }

        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return new ResultInfo(-990,"发送验证码错误/其他错误",phone);
    }
}
